<template>
  <!-- 弹出层 -->
  <el-dialog style="margin-top:-100px;" :title="studentInfo.studentId ? '修改学生' : '添加学生'" :visible.sync="dialogFormVisible">
    <el-form :rules="rules" :model="studentInfo" ref="ruleForm">
      <el-form-item label="添加照片" :label-width="formLabelWidth">
        <!-- action="/api/test" -->
        <el-upload
          class="avatar-uploader"
          action="http://127.0.0.1:3000/api/student/test"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img style="width:80px;height:120px;" v-if="studentInfo.studentPhoto" :src="studentInfo.studentPhoto" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="姓名" prop="studentName" :label-width="formLabelWidth">
        <el-input size style="width:50%;" v-model="studentInfo.studentName"></el-input>
      </el-form-item>
      <el-form-item label="性别" prop="sex" :label-width="formLabelWidth">
        <el-radio v-model="studentInfo.sex" label="男"></el-radio>
        <el-radio v-model="studentInfo.sex" label="女"></el-radio>
      </el-form-item>
      <el-form-item label="联系电话" prop="studentTel" :label-width="formLabelWidth">
        <el-input size style="width:50%;" v-model="studentInfo.studentTel"></el-input>
      </el-form-item>
      <!-- 系部、班级 -->
      <el-row :gutter="10">
        <el-col :span="14" style="padding-left:75px;">
          <el-form-item label="系部" prop="department">
            <el-select v-model="studentInfo.department" placeholder="输入系部">
              <el-option label="电子信息" value="电子信息"></el-option>
              <el-option label="会计" value="会计"></el-option>
              <el-option label="经贸" value="经贸"></el-option>
              <el-option label="机电" value="机电"></el-option>
              <el-option label="汽车" value="汽车"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="班级" prop="className">
            <el-select v-model="studentInfo.className" placeholder="输入班级">
              <el-option label="20计应1" value="20计应1"></el-option>
              <el-option label="20计应2" value="20计应2"></el-option>
              <el-option label="20计应3" value="20计应3"></el-option>
              <el-option label="20计应4" value="20计应4"></el-option>
              <el-option label="20计应5" value="20计应5"></el-option>
              <el-option label="20计应6" value="20计应6"></el-option>
              <el-option label="20计应7" value="20计应7"></el-option>
              <el-option label="20计应8" value="20计应8"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row> 
      <el-form-item label="专业" prop="major" :label-width="formLabelWidth">
        <el-input size style="width:50%;" v-model="studentInfo.major"></el-input>
      </el-form-item>
      <el-form-item label="学号" prop="studentNumber" :label-width="formLabelWidth">
        <el-input size style="width:50%;" v-model="studentInfo.studentNumber"></el-input>
      </el-form-item>
      <el-form-item label="联系QQ" prop="studentQQ" :label-width="formLabelWidth">
        <el-input style="width:50%;" v-model="studentInfo.studentQQ"  @keyup.enter.native="addOrUpdateStudent"></el-input>
      </el-form-item>
      <el-form-item :label-width="formLabelWidth">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addOrUpdateStudent">确 定</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
export default {
  name: "addOrUpdateStudent",
  props: ["getData"],
  data() {
    // 手机号验证
    let checkPhone = (rule, value, callback) => {
      if (value) {
        const reg = /^1[3456789]\d{9}$/;
        reg.test(value)
          ? callback()
          : callback(new Error("请输入正确的手机号"));
      }
    };
    // 学号验证
    let studentNumber = (rule, value, callback) => {
      if (value) {
        const reg = /^\d{12}$/;
        reg.test(value)
          ? callback()
          : callback(new Error("长度为12个字符的数字"));
      }
    };
    // QQ验证
    let studentQQ = (rule, value, callback) => {
      if (value) {
        const reg = /^\d{6,12}$/;
        reg.test(value)
          ? callback()
          : callback(new Error("长度为6-10个字符的数字"));
      }
    };
    return {
      // 控制输入宽宽度
      formLabelWidth: "120px",
      // 控制弹出层是否显示
      dialogFormVisible: false,
      // 存储单个学生信息
      studentInfo: {
        currentPage:'',
        studentPhoto: "",
        studentName: "",
        sex: "男",
        studentTel: "",
        department: "",
        className: "",
        major: "",
        studentNumber: "",
        studentQQ: "",
      },
      // 表单校验约束
      rules: {
        studentName: [{ required: true, message: "请输入学生姓名" }],
        sex: [{ required: true, message: "请选择性别" }],
        studentTel: [
          { required: true, message: "请输入手机号" },
          { validator: checkPhone, trigger: "blur" }
        ],
        department: [{ required: true, message: "请选择系部" }],
        className: [{ required: true, message: "请选择班级" }],
        major: [{ required: true, message: "请输入所学专业" }],
        studentNumber: [
          { required: true, message: "请输入学号" },
          { validator: studentNumber, trigger: "blur" }
        ],
        studentQQ: [
          { required: true, message: "请输入学生QQ", trigger: "blur" },
          { validator: studentQQ, trigger: "blur" }
        ]
      },
      // 用于暂时存在照片
      imgUrl:''
    };
  },
  mounted() {
    // 调用控制弹出层是否弹出
    this.showDialog();
  },
  methods: {
    // 全局事件总线获取父组件数据， 此作用： 用于控制弹出层是否弹出
    showDialog() {
      this.$bus.$on("showDialog", (showDialog, row) => {
        // showDialog === true
        // 使用浅拷贝： 作用： 当页面修改的时候不会立即改变数据，
        //（因为数据是 v-model 绑定的不管你有没有修改成功都会立即修改）
        // 当然这个修改只是页面内容发生了改变，但数据库中真正的数据还是未改变状态
        // 如有传递数据则存储
        if (row) {
          this.studentInfo = { ...row };
        }
        // 显示弹出层
        this.dialogFormVisible = showDialog;
      });
      this.$bus.$on('currentPage',(currentPage) => {
        this.studentInfo.currentPage = currentPage
      })  
    },
    // 添加或修改学生
    addOrUpdateStudent() {
      // 表单校验是否ok
      this.$refs.ruleForm.validate(async isTrue => {
        
        if (isTrue) {
          // 加载组件
          const loading = this.$loading({
            lock: true,
            text: "请求中",
            spinner: "el-icon-loading",
            background: "rgba(0, 0, 0, 0.7)"
          });
          try {
            // 获取添加学生是否成功
            let result = await this.$store.dispatch( "studentInfo/getAddOrUpdateStudent",this.studentInfo);
            // 当为 200 成功并加提示
            if (result.code === 200) {
              this.$message({
                message: this.studentInfo.studentId ? "修改成功" : "添加成功",
                type: "success"
              });
              // 只有成功的时候才会关闭 控制显示框是否展示
              this.dialogFormVisible = false;
              // 当成功后加载立即关闭
              loading.close();
              // 再次获取数据
              this.studentInfo.currentPage ? this.getData(this.studentInfo.currentPage) : this.getData()
            }
          } catch (error) {
            // 错误提示出现之前先关闭
            loading.close();
            // 失败时提示信息
            this.$message({
              message: this.studentInfo.studentId
                ? `*_*,${error.message}`
                : `#_#,${error.message}`,
              type: "error"
            });
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 上传图片按钮
    uploadStudentPhotoBtn() {
      alert("辞工能正在开发中~~~");
    },
    // 照片上传成功事件
    handleAvatarSuccess(res, file) {
      // console.log(res,file)
      // URL.createObjectURL: 创建图片路径
      
      this.imgUrl = URL.createObjectURL(file.raw);
      this.studentInfo.studentPhoto = this.imgUrl
    },
    // 图片上传成功之前
    beforeAvatarUpload(file) {
      // console.log(file)
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    // 给父组件传递方法 每次进入清楚表单校验
    clearCheck(){
      // 第一次以上来 this.$refs.ruleForm 是 undefined,
      this.$refs.ruleForm && this.$refs.ruleForm.resetFields();
    }
  }
};
</script>

<style lang="less" scoped>
// 上传图片样式
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
  border: 1px solid #cecaca;
}
.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style>